package cn.tedu.listener;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

/**
 * Application Lifecycle Listener implementation class OnLineUserListener
 *
 */
public class OnLineUserListener implements HttpSessionAttributeListener {
	private int count=0;
    /**
     * Default constructor. 
     */
    public OnLineUserListener() {
        System.out.println("统计登录人数监听器生命周期开始");
    }

	/**
     * @see HttpSessionAttributeListener#attributeAdded(HttpSessionBindingEvent)
     */
    public void attributeAdded(HttpSessionBindingEvent event)  { 
    	System.out.println("说明session对象中被添加数据了");
    	//因为session中可以被setAttribute(name,value)
    	//即往session对象中放置多个键值对
    	String name=event.getName();
    	if("user_name".equals(name)) {
    		//说明session中的user_name中的数据被添加了
    		count++;
    		HttpSession session=event.getSession();
    		ServletContext application=session.getServletContext();
    		application.setAttribute("onLineUser", count);
    	}
    }

	/**
     * @see HttpSessionAttributeListener#attributeRemoved(HttpSessionBindingEvent)
     */
    public void attributeRemoved(HttpSessionBindingEvent event)  { 
    	System.out.println("说明session对象中被移除数据了");
    	String name=event.getName();
    	if("user_name".equals(name)) {
    		//说明session中的user_name中的数据被添加了
    		count--;
    		HttpSession session=event.getSession();
    		ServletContext application=session.getServletContext();
    		application.setAttribute("onLineUser", count);
    	}
    }

	/**
     * @see HttpSessionAttributeListener#attributeReplaced(HttpSessionBindingEvent)
     */
    public void attributeReplaced(HttpSessionBindingEvent event)  { 
    	System.out.println("说明session对象中被替换数据了");
    }
	
}
